package com.hexus.eve.utils;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.beimin.eveapi.core.ApiException;
import com.beimin.eveapi.server.ServerStatusParser;
import com.beimin.eveapi.server.ServerStatusResponse;


import com.hexus.eve.application.Constants;

@Component("serverStatus")
public class ServerStatus {
	private Logger log = Logger.getLogger(this.getClass());
	
	private static Boolean online = false;
	private static Boolean error = true;
	private static String errorText = "";
	private static Integer onlinePlayers = 0;
	private static Date lastDownTime = new Date();
	
	private class ServerStatusThread extends Thread{
		private Long sleepTime; 
		ServerStatusThread(Long sleepTime) {
			this.sleepTime = sleepTime;
		}
		@Override
		public void run() {
			while(true) {
				try {
					synchronized (this) {
						Boolean onlineStatusBeforeCheck = online;
						error = true;

						ServerStatusParser status = ServerStatusParser.getInstance();
						
						try {
							ServerStatusResponse response = status.getServerStatus();
							if(response.hasError()){
								online = false;
								errorText = response.getError().getError();
								log.error("Server status response error: " + errorText);
							} else {
								online = response.isServerOpen();
								onlinePlayers = response.getOnlinePlayers();
								error = false;								
								errorText = "";								
							}
						} catch (ApiException e) {
							online = false;
							errorText = e.getMessage();
							log.error("Server status API exception: " + errorText);
						}
						
						if(onlineStatusBeforeCheck && !online) {
							log.info("EVE Server is NOT AVAILABLE");
							lastDownTime = new Date();
						}
						
						if(!onlineStatusBeforeCheck && online) {
							log.info("EVE Server is AVAILABLE");
						}
						
						sleep(sleepTime);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} //try
			} //synchronized
		}//while
	}

	@Autowired
	public ServerStatus(Constants constants){
		log.debug("Starting ServerStatus checking thread");
		ServerStatus.ServerStatusThread serverStatusThread = new ServerStatus.ServerStatusThread(Long.valueOf(constants.getProperty(Constants.PropertyNames.SERVER_STATUS_SLEEP_TIME)));
		serverStatusThread.start();
	}

	public static Boolean isOnline() {
		return online;
	}

	public static String getErrorText() {
		return errorText;
	}

	public static Boolean hasError() {
		return error;
	}

	public static Integer getOnlinePlayers() {
		return onlinePlayers;
	}	

	public static Date getLastDownTime() {
		return lastDownTime;
	}	

}
